package org.example.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.example.enums.BizCodeEnum;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class JsonData {
    private int code;

    private Object data;

    private String msg;

    //自动转换数据类型
    public <T> T getData(TypeReference<T> typeReference){
        return JSON.parseObject(JSON.toJSONString(data),typeReference);
    }

    //成功，无数据返回
    public static JsonData buildSuccess() {
        return new JsonData(0, null, null);
    }

    //成功，需要返回数据
    public static JsonData buildSuccess(Object data) {
        return new JsonData(0, data, null);
    }

    //失败，错误码为-1，需要描述
    public static JsonData buildError(String msg) {
        return new JsonData(-1, null, msg);
    }

    //失败，自定义错误码，需要描述
    public static JsonData buildCodeAndMsg(int code, String msg) {
        return new JsonData(code, null, msg);
    }

    //传入枚举，返回数据
    public static JsonData buildResult(BizCodeEnum codeEnum) {
        return buildCodeAndMsg(codeEnum.getCode(), codeEnum.getMessage());
    }
}
